package main

import (
	"Test/1goAdvanced/chatroom/common"
	"bufio"
	"fmt"
	"net"
	"strings"
	"sync"
)

func main() {
	//server中的锁不用初始化
	server := &common.Server{
		//Clients: make(map[string]*common.Client),
		Clients: sync.Map{},
	}
	listener, err := net.Listen("tcp", "0.0.0.0:8888")
	if err != nil {
		// handle error
		fmt.Println("服务器启动失败:", err)
		return
	}
	defer listener.Close()
	for {
		conn, err2 := listener.Accept()
		if err2 != nil {
			fmt.Println("接受连接失败:", err2)
			// handle error
			continue
		}
		//读取用户名
		reader := bufio.NewReader(conn)
		username, err3 := reader.ReadString('\n')
		if err3 != nil {
			fmt.Println("用户姓名读取失败", err3)
			continue
		}
		username = strings.TrimSpace(username)
		//将用户添加到客户端
		if !server.AddClient(username, conn) {
			//判断得出用户名重复
			continue
		}
		//获取map中的用户
		//server.Mutex.Lock()
		value, ok := server.Clients.Load(username)
		if !ok {
			continue
		}
		//server.Mutex.Unlock()
		//需要进行value断言
		client := value.(*common.Client)

		//启动处理客户端的协程
		go server.ProcessClient(client)
		//go handleConnection(conn)
	}
}
